<template>
    <div class="register-container">
        <el-card class="register-box">
            <template #header>
                <h2 class="register-title">用户注册</h2>
            </template>
            <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-position="top"
                @keyup.enter="handleRegister">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="registerForm.username" placeholder="请输入用户名 (3-50个字符)" prefix-icon="User" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="registerForm.password" type="password" placeholder="请输入密码 (6-50个字符)"
                        prefix-icon="Lock" show-password />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码"
                        prefix-icon="Lock" show-password />
                </el-form-item>
                <el-form-item label="真实姓名" prop="realName">
                    <el-input v-model="registerForm.realName" placeholder="请输入真实姓名（可选）" prefix-icon="User" />
                </el-form-item>
                <el-form-item label="电子邮箱" prop="email">
                    <el-input v-model="registerForm.email" placeholder="请输入电子邮箱（可选）" prefix-icon="Message" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="registerForm.gender">
                        <el-radio :label="0">未知</el-radio>
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :loading="loading" class="register-btn"
                        @click="handleRegister">注册</el-button>
                </el-form-item>
                <div class="login-link">
                    <span>已有账号?</span>
                    <el-link type="primary" :underline="false" @click="$router.push('/login')">返回登录</el-link>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { userService } from '@/http/userService'
import { ElMessage } from 'element-plus'
import { User, Lock, Message } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

const router = useRouter()
const registerFormRef = ref<FormInstance>()
const loading = ref(false)

const registerForm = reactive({
    username: '',
    password: '',
    confirmPassword: '',
    realName: '',
    email: '',
    gender: 0
})

const validateConfirmPassword = (rule: any, value: string, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}

const validateEmail = (rule: any, value: string, callback: any) => {
    if (value === '') {
        callback()
    } else {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        if (emailRegex.test(value)) {
            callback()
        } else {
            callback(new Error('请输入有效的电子邮箱'))
        }
    }
}

const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 50, message: '用户名长度应为3-50个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 50, message: '密码长度应为6-50个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: validateConfirmPassword, trigger: 'blur' }
    ],
    email: [
        { validator: validateEmail, trigger: 'blur' }
    ]
})

const handleRegister = async () => {
    if (!registerFormRef.value) return

    await registerFormRef.value.validate(async (valid) => {
        if (!valid) return

        loading.value = true

        try {
            const response = await userService.register({
                username: registerForm.username,
                password: registerForm.password,
                realName: registerForm.realName || undefined,
                email: registerForm.email || undefined,
                gender: registerForm.gender
            })

            if (response.success) {
                ElMessage.success('注册成功，即将跳转到登录页面...')

                // 清空表单
                registerForm.username = ''
                registerForm.password = ''
                registerForm.confirmPassword = ''
                registerForm.realName = ''
                registerForm.email = ''
                registerForm.gender = 0

                // 3秒后跳转到登录页
                setTimeout(() => {
                    router.push('/login')
                }, 3000)
            } else {
                ElMessage.error(response.message || '注册失败，请稍后再试')
            }
        } catch (error) {
            console.error('注册失败:', error)
            ElMessage.error('注册失败，请稍后再试')
        } finally {
            loading.value = false
        }
    })
}
</script>

<style scoped>
.register-container {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f5f7fa;
}

.register-box {
    width: 450px;
    max-width: 90%;
}

.register-title {
    text-align: center;
    margin: 0;
    font-size: 24px;
    color: #333;
    font-weight: normal;
}

.register-btn {
    width: 100%;
}

.login-link {
    text-align: center;
    margin-top: 15px;
    font-size: 14px;
    color: #606266;
}
</style>